package com.shadowlight.hero_story.cmdHandler;

import com.alibaba.fastjson.JSONObject;
import com.shadowlight.hero_story.MysqlSessionFactory;
import com.shadowlight.hero_story.asyncOperation.AsyncOperation;
import com.shadowlight.hero_story.asyncOperation.IAsyncOperation;
import com.shadowlight.hero_story.login.database.IUserEntityDao;
import com.shadowlight.hero_story.login.database.entity.UserEntity;
import com.shadowlight.hero_story.msg.GameMsgProtocol;
import com.shadowlight.hero_story.pojo.User;
import com.shadowlight.hero_story.pojo.UserRepository;
import com.shadowlight.hero_story.util.RedisUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import redis.clients.jedis.Jedis;

/**
 * @Description 选英雄处理器
 * @Author cz
 * @Date 2022/3/2
 */
@Slf4j
public class SelectHeroCmdHandler implements ICmdHandler<GameMsgProtocol.SelectHeroCmd> {

    @Override
    public void handle(ChannelHandlerContext channelHandlerContext, GameMsgProtocol.SelectHeroCmd msg) {
        //获取选英雄结果
        String heroAvatar = msg.getHeroAvatar();
        log.debug("用户选择了英雄: {}", heroAvatar);
        Integer id = (Integer) channelHandlerContext.channel().attr(AttributeKey.valueOf("userId")).get();
        if (id == null) return;
        //存储用户选择的英雄
        User user = UserRepository.getInstance().getUserById(id);
        user.setHeroAvatar(heroAvatar);
        UserRepository.getInstance().save(user);
        try (Jedis redis = RedisUtil.getRedis()) {
            UserEntity userEntity = JSONObject.parseObject(redis.hget("User_" + user.getId(),
                    "BasicInfo"), UserEntity.class);
            userEntity.setHeroAvatar(heroAvatar);
            redis.hset("User_" + user.getId(), "BasicInfo", JSONObject.toJSONString(userEntity));

            //更新数据库中用户选择的英雄，异步更新
            AsyncOperation.getInstance().process(new IAsyncOperation() {

                @Override
                public void doAsync() {
                    try (SqlSession mySqlSession = MysqlSessionFactory.openSession()) {
                        IUserEntityDao userEntityDao = mySqlSession.getMapper(IUserEntityDao.class);
                        userEntityDao.updateHeroAvatarById(userEntity.getId(), userEntity.getHeroAvatar());
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }

                @Override
                public void doFinish() {
                    GameMsgProtocol.SelectHeroResult.Builder selectHeroResultBuilder = GameMsgProtocol.SelectHeroResult.newBuilder();
                    selectHeroResultBuilder.setHeroAvatar(heroAvatar);

                    GameMsgProtocol.SelectHeroResult result = selectHeroResultBuilder.build();
                    channelHandlerContext.channel().writeAndFlush(result);
                }
            });
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
